package com.briup.jd2511.web02.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;

@RestController
public class OriginalController {
    @RequestMapping(value = "/original",method = RequestMethod.GET)
    public String original(HttpServletRequest request){
        // 获取请求对象中的数据，request对象可以直接用
        System.out.println(request.getRequestURI());
        System.out.println(request.getServletPath());
        System.out.println(request.getHeader("HOST"));
        System.out.println(request.getContextPath());
        System.out.println(request.getServerPort());
        System.out.println(request.getServerName());
        System.out.println(request.getProtocol());
        System.out.println(request.getRequestURL());
        return "abc";
    }

    @RequestMapping(value = "/getParams",method = {RequestMethod.GET,RequestMethod.POST})
    public String getParams(HttpServletRequest request){
        // 获取参数，name和age，类型都是字符串
        String name = request.getParameter("name");
        String age = request.getParameter("age");

        return name+ " : "+age;
    }

    // 使用原始的request和response对象实现登陆
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public void login(HttpServletRequest request,
                      HttpServletResponse response) throws IOException {
        // 从请求中获取数据
        // 编辑到响应里
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        PrintWriter writer = response.getWriter();

        // 验证
        if("admin".equals(username) && "admin".equals(password)){
            // 设置响应头
            response.setStatus(200);
            response.setHeader("Content-Type","text/plain;charset=UTF-8");
            response.setHeader("Content-Length","7");
            // 设置响应体，使用流写出去

            writer.println("success");

        }else {
            System.out.println("错误的逻辑...");
            // 设置响应头
            response.setStatus(200);
            response.setHeader("Content-Type","text/plain;charset=UTF-8");
            response.setHeader("Content-Length","13");
            // 设置响应体
            writer.println("error");
            System.out.println("abc");
        }
        writer.flush();
        writer.close();
    }
}
